import Vue from 'vue'
import App from './app.vue'
import router from './router'
import axios from 'axios'
import filter from "./filter/filter";
import store from '@/store/index';
Vue.config.productionTip = false;
Vue.prototype.$ajax = axios;

//事件总线EventBus
Vue.prototype.$event = new Vue();
new Vue({
  store,
  router,
  render: h => h(App),
}).$mount('#app');
// 全局过滤器
Object.keys(filter).forEach(key => {
  Vue.filter(key, filter[key])
});

// 解决每次ajax请求，对应的sessionId不一致的问题
axios.defaults.withCredentials = true;

/**
 * axios拦截器
 */
axios.interceptors.request.use(function (config) {
  console.log("请求：", config);
  let token = Tool.getLoginMember().token;
  if (Tool.isNotEmpty(token)) {
    config.headers.token = token;
    console.log("请求headers增加token:", token);
  }
  return config;
}, error => {});
axios.interceptors.response.use(function (response) {
  console.log("返回结果：", response);
  return response;
}, error => {
  console.log("返回拦截：", error.response);
  let response = error.response;
  const status = response.status;
  if (status === 401) {
    // 判断状态码是401 跳转到登录
    // this.$store.commit('setiflogin',false)
    // store.state.iflogin = false;
    store.state.iflogin = !store.state.iflogin;
    console.log("未登录，跳到登录页面");
    Tool.setLoginMember(null);
    Toast.warning("用户无权限访问该功能。可能未登录/登录用户无该功能权限。")
    //router.push('/login');//todo 怎么实现不跳转页面，并且弹出登录框
  }
  if(status===500){
    Toast.error("服务器错误，请求失败。")
  }
  // store.state.iflogin = true;
/*  return {
    data: {
      success: false,
      message: "请重新登录"
    }
  };*/
});

// 路由登录拦截
router.beforeEach((to, from, next) => {
  // 要不要对meta.loginRequire属性做监控拦截
  if (to.matched.some(function (item) {
    return item.meta.loginRequire
  })) {
    let loginMember = Tool.getLoginMember();
    if (Tool.isEmpty(loginMember)) {
      Toast.warning("未登录，请登录后操作。")
      next('/login');//todo 怎么实现不跳转页面，并且弹出登录框
    } else {
      next();
    }
  } else {
    next();
  }
});


